package com.jqsoft.launcher.print;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.pdf.PdfDocument;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
import android.print.PageRange;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintDocumentInfo;
import android.print.pdf.PrintedPdfDocument;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by Administrator on 2017-10-13.
 */


@SuppressLint("NewApi")
public class MyPrintDocumentAdapter extends PrintDocumentAdapter {
    private Context context;
    private PrintedPdfDocument mPdfDocument;
    private  int totalPages;

    public MyPrintDocumentAdapter(Context context) {
        super();
        this.context=context;
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras) {
        mPdfDocument = new PrintedPdfDocument(context, newAttributes);

        if (cancellationSignal.isCanceled() ) {
            callback.onLayoutCancelled();
            return;
        }

        int pages = computePageCount(newAttributes);
        totalPages = pages;

        if (pages > 0) {
            String name = PrintUtil.getRandomUuid();
            PrintDocumentInfo info = new PrintDocumentInfo
                    .Builder(name+".pdf")
                    .setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
                    .setPageCount(pages)
                .build();
            callback.onLayoutFinished(info, true);
        } else {
            callback.onLayoutFailed("Page count calculation failed.");
        }
    }

    @Override
    public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback) {
//        PageRange pr = pages[0];
        for (int i = 0; i < totalPages; i++) {
//            if (i>=pr.getStart()&&i<=pr.getEnd()) {
                PdfDocument.Page page = mPdfDocument.startPage(i);

                if (cancellationSignal.isCanceled()) {
                    callback.onWriteCancelled();
                    mPdfDocument.close();
                    mPdfDocument = null;
                    return;
                }

                drawPage(page);

                mPdfDocument.finishPage(page);
//            }
        }

        try {
            mPdfDocument.writeTo(new FileOutputStream(
                    destination.getFileDescriptor()));
        } catch (IOException e) {
            callback.onWriteFailed(e.toString());
            return;
        } finally {
            mPdfDocument.close();
            mPdfDocument = null;
        }
        PageRange[] writtenPages = pages;
        callback.onWriteFinished(writtenPages);
    }

    @Override
    public void onFinish() {
        super.onFinish();
    }

    private int computePageCount(PrintAttributes printAttributes) {
        int itemsPerPage = 4;

        PrintAttributes.MediaSize pageSize = printAttributes.getMediaSize();
        if (!pageSize.isPortrait()) {
            itemsPerPage = 6;
        }

        int printItemCount = getPrintItemCount();

        return (int) Math.ceil((double)printItemCount / itemsPerPage);
    }

    private int getPrintItemCount() {
        return 10;
    }

    private void drawPage(PdfDocument.Page page) {
        Canvas canvas = page.getCanvas();

        int titleBaseLine = 72;
        int leftMargin = 54;

        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setTextSize(36);
        canvas.drawText("标题", leftMargin, titleBaseLine, paint);

        paint.setTextSize(11);
        canvas.drawText("段落内容", leftMargin, titleBaseLine + 25, paint);

        paint.setColor(Color.BLUE);
        canvas.drawRect(100, 100, 172, 172, paint);
    }
}
